package com.github.phoenics.newlives.common.interceptor;

import com.github.phoenics.newlives.common.NoRestWrap;
import com.github.phoenics.newlives.common.base.RestResponse;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.core.MethodParameter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Collection;
import java.util.List;

/**
 * 自定义输出
 *
 * @author Phoenics Chow
 * on 2019年09月24日
 */
public class HandlerMethodReturnValueHandlerRest implements HandlerMethodReturnValueHandler {
    private HandlerMethodReturnValueHandler restObject;
    private List<String> nowrapUrls= Lists.newArrayList("/actuator", "/health");
    public HandlerMethodReturnValueHandlerRest(HandlerMethodReturnValueHandler restObject){
        this.restObject=restObject;
    }
    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return restObject.supportsReturnType(methodParameter);
    }

    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        String uri = ((ServletWebRequest) nativeWebRequest).getRequest().getRequestURI();
        Collection<String> result = Collections2.filter(nowrapUrls,n -> StringUtils.containsIgnoreCase(uri, n));
        if (o instanceof RestResponse ||
                result.size()>0 ||
                methodParameter.getMethod().getAnnotation(NoRestWrap.class) != null ||
                methodParameter.getDeclaringClass().getAnnotation(NoRestWrap.class) != null) {
        }else{
            o=RestResponse.success(o);
        }
        restObject.handleReturnValue(o, methodParameter, modelAndViewContainer, nativeWebRequest);
    }
}
